package com.bsj.pay.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bsj.pay.common.Result;
import com.bsj.pay.model.AccountBean;
import com.bsj.pay.model.ChargeAccountBean;
import com.bsj.pay.model.PartnerBean;
import com.bsj.pay.service.AccountService;
import com.bsj.pay.service.ChargeAccountService;
import com.bsj.pay.service.LogService;
import com.bsj.pay.service.PartnerService;
import com.bsj.pay.service.impl.OrderServiceImpl;
import com.bsj.pay.util.HttpUtil;
import com.bsj.pay.util.security.Base64;
import com.bsj.pay.util.security.MD5;

@RequestMapping("/api")
@Controller
public class ReceiveController {
	
	private static final Logger log = LogManager.getLogger(ReceiveController.class);
	
	@Autowired
	private ChargeAccountService chargeAccountService;
	
	@Autowired
	private PartnerService partnerService;
	
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private LogService logService;
	
	@ResponseBody
	@RequestMapping(value = "/receiveOrder")
	public Result receiveOrder(HttpServletRequest request,HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		String partner_id=request.getParameter("partner_id");
		String partner_order_no=request.getParameter("partner_order_no");
		String account=request.getParameter("account");
		String amount=request.getParameter("amount");
		String type = request.getParameter("type");
		String area = request.getParameter("area");
		String notify_url=request.getParameter("notify_url");
		String sign=request.getParameter("sign");
		String req_ip=HttpUtil.getIpAddr(request);
		Result result = new Result();

		if (StringUtils.isEmpty(account)) {
			result.setCode(101);
			result.setMsg("参数缺失account");
			result.setData("");
			return result;
		}
		if (StringUtils.isEmpty(partner_id)) {
			result.setCode(101);
			result.setMsg("参数缺失partner_id");
			result.setData("");
			return result;
		}
		if (StringUtils.isEmpty(partner_order_no)) {
			result.setCode(101);
			result.setMsg("参数缺失partner_order_no");
			result.setData("");
			return result;
		}
		if (StringUtils.isEmpty(amount)) {
			result.setCode(101);
			result.setMsg("参数缺失amount");
			result.setData("");
			return result;
		}
		if (StringUtils.isEmpty(type)) {
			result.setCode(101);
			result.setMsg("参数缺失type");
			result.setData("");
			return result;
			
		}
		if (StringUtils.isEmpty(area)) {
			result.setCode(101);
			result.setMsg("参数缺失area");
			result.setData("");
			return result;
			
		}
		if (StringUtils.isEmpty(notify_url)) {
			result.setCode(101);
			result.setMsg("参数缺失notify_url");
			result.setData("");
			return result;
			
		}
		if (StringUtils.isEmpty(sign)) {
			result.setCode(101);
			result.setMsg("参数缺失sign");
			result.setData("");
			return result;
		}
		try {
			PartnerBean partner = partnerService.getById(Long.parseLong(partner_id));
			if(partner==null)
			{
				result.setCode(102);
				result.setMsg("合作商不存在");
				result.setData("");
				return result;
			}
			if(partner.getStatus()==0)
			{
				result.setCode(103);
				result.setMsg("合作商被禁用");
				result.setData("");
				return result;
			}
			if(!StringUtils.isEmpty(partner.getBind_ip())&&!partner.getBind_ip().contains(req_ip)) {
				result.setCode(104);
				result.setMsg("非法请求");
				result.setData("");
				return result;
			}
			if(partner.getQuota()<Integer.parseInt(amount))
			{
				result.setCode(105);
				result.setMsg("授信额度不足");
				result.setData("");
				return result;
			}
			String signstr=partner_id+partner_order_no+account+amount+type+area+notify_url;
			log.info("signstr:"+signstr);
			String md5=MD5.getMD5(signstr+partner.getApi_key());
			log.info("md5:"+md5);
			if(!sign.equals(md5))
			{
				result.setCode(106);
				result.setMsg("签名验证失败");
				result.setData("");
				return result;
			}
			ChargeAccountBean insertModel=new ChargeAccountBean();
			insertModel.setPartner_id(partner.getId());
			insertModel.setAccount(account);
			insertModel.setAmount(Integer.parseInt(amount));
			insertModel.setPartner_order_no(partner_order_no);
			insertModel.setNotify_url(notify_url);
			insertModel.setArea(area);
			insertModel.setType(Integer.parseInt(type));
			return chargeAccountService.receiveOrder(insertModel);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(500);
			result.setMsg("server error");
			result.setData("");
			return result;
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/queryOrder")
	public Result queryOrder(HttpServletRequest request,HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		String partner_id=request.getParameter("partner_id");
		String partner_order_no=request.getParameter("partner_order_no");
		String sign=request.getParameter("sign");
		String req_ip=HttpUtil.getIpAddr(request);
		Result result = new Result();
		if (StringUtils.isEmpty(partner_id)) {
			result.setCode(101);
			result.setMsg("参数缺失partner_id");
			result.setData("");
			return result;
		}
		if (StringUtils.isEmpty(partner_order_no)) {
			result.setCode(101);
			result.setMsg("参数缺失partner_order_no");
			result.setData("");
			return result;
		}
		if (StringUtils.isEmpty(sign)) {
			result.setCode(101);
			result.setMsg("参数缺失sign");
			result.setData("");
			return result;
		}
		try {
			PartnerBean partner = partnerService.getById(Long.parseLong(partner_id));
			if(partner==null)
			{
				result.setCode(102);
				result.setMsg("合作商不存在");
				result.setData("");
				return result;
			}
			if(partner.getStatus()==0)
			{
				result.setCode(103);
				result.setMsg("商户被禁用");
				result.setData("");
				return result;
			}
			if(!StringUtils.isEmpty(partner.getBind_ip())&&!partner.getBind_ip().equals(req_ip)) {
				result.setCode(104);
				result.setMsg("非法请求");
				result.setData("");
				return result;
			}
			String signstr=partner_id+partner_order_no;
			String md5=MD5.getMD5(signstr+partner.getApi_key());
			if(!sign.equals(md5))
			{
				result.setCode(105);
				result.setMsg("签名验证失败");
				result.setData("");
				return result;
			}
			ChargeAccountBean queryModel=new ChargeAccountBean();
			queryModel.setPartner_order_no(partner_order_no);
			List<ChargeAccountBean> chargeAccountList=chargeAccountService.queryList(queryModel);
			if(chargeAccountList==null||chargeAccountList.size()==0)
			{
				result.setCode(106);
				result.setMsg("订单不存在");
				result.setData("");
				return result;
			}
			ChargeAccountBean chargeAccount=chargeAccountList.get(0);
			Map<String,String> map=new HashMap<String,String>();
			map.put("status", String.valueOf(chargeAccount.getCharge_status()));
			map.put("partner_id", String.valueOf(chargeAccount.getPartner_id()));
			map.put("partner_order_no", chargeAccount.getPartner_order_no());
			map.put("account", chargeAccount.getAccount());
			map.put("amount", String.valueOf(chargeAccount.getAmount()));
			int charge_amount=chargeAccountService.getChargeSuccAmountById(chargeAccount.getId());
			map.put("charge_amount", String.valueOf(charge_amount));
			map.put("type", String.valueOf(chargeAccount.getType()));
			result.setCode(1);
			result.setMsg("请求成功");
			result.setData(map);
			return result;
		} catch (Exception e) {
			result.setCode(500);
			result.setMsg(e.getMessage());
			result.setData("");
			return result;
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/testPartnerNotifyUrl.html")
	public String testPartnerNotifyUrl(HttpServletRequest request,HttpServletResponse response) throws IOException {
		return "success";
	}
	
	@ResponseBody
	@RequestMapping(value = "/receiveCookies")
	public String receiveCookies(HttpServletRequest request,HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		String phone=request.getParameter("Phone");
		String operator=request.getParameter("Operator");
		String cookies=request.getParameter("Cookies");
		if (StringUtils.isEmpty(phone)) {
			return "参数缺失Phone";
		}
		if (StringUtils.isEmpty(operator)) {
			return "参数缺失Operator";
		}
		if (StringUtils.isEmpty(cookies)) {
			return "参数缺失Cookies";
		}
		try {
			AccountBean addModel=new AccountBean();
			addModel.setAccount(phone);
			addModel.setOperator(operator);
			if(accountService.count(addModel)>0)
			{
				return "账号已存在，添加失败";
			}
			cookies=Base64.decodeString(cookies);
			addModel.setLogin_cookie(cookies);
			addModel.setQuota(1000000);
			addModel.setCreate_time(System.currentTimeMillis()/1000);
			addModel.setCreate_user(0l);
			accountService.insert(addModel);
			log.info("新增"+operator+"账号:"+addModel.getAccount());
			logService.addLog(request, "新增"+operator+"账号:"+addModel.getAccount());
			OrderServiceImpl.lastActiveTime=System.currentTimeMillis()/1000;
			return "success";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return e.getMessage();
		}
	}
}
